/*
 * @lc app=leetcode.cn id=914 lang=typescript
 *
 * [914] 卡牌分组
 */

// @lc code=start
function hasGroupsSizeX(deck: number[]): boolean {
  const gcd = (a: number, b: number) => (b === 0 ? a : gcd(b, a % b));
  const map = new Map<number, number>();

  for (const num of deck) {
    map.set(num, (map.get(num) ?? 0) + 1);
  }

  let x = -1;
  // 计算所有元素数量的最大公约数
  for (const [_, count] of map) {
    if (x === -1) x = count;
    else x = gcd(x, count);
    if (x === 1) break;
  }
  // 最大公约数大于1即可
  return x > 1;
}
// @lc code=end
